<template>
  <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home/networkdisk' }">网盘</el-breadcrumb-item>
        <el-breadcrumb-item>{{this.$route.name}}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-row>
      <el-col :span="24">
        <el-col :span="3" class="func">
          <div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              prefix-icon="el-icon-search"
              v-model="searchFile"
              size="mini"
              @keyup.enter.native="SearchFile"
            ></el-input>
          </div>
        </el-col>
        <el-upload
          class="upload-demo"
          ref="upload"
          action="#"
          :on-change="changeFile"
          :show-file-list="false"
          :auto-upload="false"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button
            style="margin-left: 10px;"
            size="small"
            type="success"
            @click="sendRequest"
          >上传到服务器</el-button>
        </el-upload>
      </el-col>
      <div class="progress">
        <span>上传进度：{{ Total|totalText }}%</span>
        <!-- <le-link tpye="primary" v-if="total>0 && total<100" @click="handleBtn">{{ btn|btnText }}</le-link> -->
      </div>
    </el-row>
    <ul class="menu">
      <!-- <div slot="empty" style="text-align: left;">暂无数据</div> -->
      <el-table :data="fileInfos" style="width: 100%" :border="true">
        <el-table-column prop="id" label="#" width="100"></el-table-column>
        <el-table-column prop="file_name" label="文件名" width="250"></el-table-column>
        <el-table-column prop="create_at" label="创建时间" width="250"></el-table-column>
        <el-table-column prop="size" label="大小(MB/Byte)" width="130"></el-table-column>
        <el-table-column label="文件">
          <template slot-scope="{row}">
            <div v-if="row.type=='jpg'  || row.type=='jpeg'  || row.type=='png'">
              <el-image style="width: 100px; height: 100px" :src="row.file_link" fit="scale-down"></el-image>
            </div>
            <div v-else-if="row.type=='yaml' || row.type=='yml'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/YAML.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else-if="row.type=='txt'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/format-txt.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else-if="row.type=='zip'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/zip.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else-if="row.type=='mp4'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/mp4.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else-if="row.type=='exe'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/exe.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else-if="row.type=='pdf'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/pdf.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else-if="row.type=='sh'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/sh.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else-if="row.type=='docx' || row.type=='doc'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/file-word-fill.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else-if="row.type=='xlsx' || row.type=='xlx'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/file-excel-fill.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else-if="row.type=='pptx' || row.type=='ppt'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/file-ppt-fill.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else-if="row.type=='tar' || row.type=='gz'">
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/TAR.png')"
                fit="scale-down"
              ></el-image>
            </div>
            <div v-else>
              <el-image
                style="width: 6%;"
                :src="require('@/assets/static/image/unknown.png')"
                fit="scale-down"
              ></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="文件类型" width="100"></el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              @click="download(scope.row)"
              type="primary"
              icon="el-icon-download"
              size="small"
            ></el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="fileDel(scope.row)"></el-button>
            <el-button type icon="el-icon-share" size="small" @click="share_create(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </ul>
    <div style="margin-top: 10px;">
      <div class="block">
        <!-- <el-pagination
          @size-change="handleSizeChange"
          @next-click="nextChange"
          @prev-click="prevChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>-->
        <!-- 分页 -->
        <div class="pagintaion">
          <Pagintaion
            :paginationData="paginationData"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></Pagintaion>
        </div>
      </div>
    </div>

    <!-- 分享成功后的弹出框 -->
    <el-dialog title="分享成功" :visible.sync="Share_success_dialogVisible" width="30%">
      <div class="share_font" id="share_url">{{shareURL}}</div>
      <el-button
        size="mini"
        class="copy-link"
        data-clipboard-target="#share_url"
        @click="share_copy"
      >复制</el-button>
    </el-dialog>
    <!-- 分享成功后的弹出框 -->
  </div>
</template>

<script>
import SparkMd5 from "spark-md5";
import { filePares } from "@/utils/index";
import Clipboard from "clipboard";
import Pagintaion from "../../components/pagination/pagination.vue";
import {
  ObjectAll,
  FileUpload,
  SearchFiles,
  FileDel,
  DownloadFile,
  MegerChunks,
  ShareFile
} from "@/utils/http";
export default {
  components: {
    Pagintaion
  },
  data() {
    return {
      showQr: null,

      paginationData: {
        limit: 10,
        page: 1,
        total: 0
      },
      fileInfos: [], // 表格数据
      searchFile: "", // 文件搜索
      checkboxGroup1: false,
      checkList: [],
      showImg: false,
      fileName: "",
      partList: [],
      hash: "",
      Total: 0,
      // total: 0,
      video: null,
      btn: false,
      loading: false, // 加载动画
      Share_success_dialogVisible: false, // 分享成功后的弹出框
      shareURL: "" // 分享地址
    };
  },
  filters: {
    // btnText(btn) {
    //   return btn ? "继续" : "暂停";
    // },
    totalText(Total) {
      return Total > 100 ? 100 : Total;
    }
  },
  methods: {
    show(id) {
      this.showQr = id;
    },
    showout() {
      this.showQr = 0;
    },
    // checkbox触发事件
    handleChange(id, filename) {
      let root_dir = this.$route.query.rootdir;

      let file_id = {
        id: id,
        objectpath: root_dir + "/" + filename
      };

      this.checkList.push(file_id);
    },

    async changeFile(file) {
      if (!file) return;
      this.fileName = file.name;
      file = file.raw;
      // 解析为buffer数据
      // 把文件切片处理：把一个文件分隔成好几个部分（固定数量/固定大小）
      let buffer = await filePares(file, "buffer"),
        spark = new SparkMd5.ArrayBuffer(),
        hash,
        suffix;
      spark.append(buffer); // 根据字节流生成hash值
      hash = spark.end();
      // 获取文件后缀
      suffix = file.name.split(".")[file.name.split(".").length - 1];

      // 生成切片信息，100个切片
      let partList = [], // 切片数组
        partsize = file.size / 50, // 切片大小
        cur = 0; // 记录当前切片
      for (let i = 0; i < 50; i++) {
        let item = {
          chunk: file.slice(cur, cur + partsize),
          filename: `${hash}_${i}.${suffix}`
        };
        cur += partsize; // 下次切片是在cur + partsize基础上进行切片
        partList.push(item);
        // this.Total += i;
      }

      this.partList = partList;
      this.hash = hash;
      // this.sendRequest();
    },
    async sendRequest() {
      let query = {
        bucket_id: this.$route.query.bucketid,
        bucket_name: this.$route.query.bucketname,
        catalogue_id: this.$route.query.id,
        catalogue_name: this.$route.query.rootdir
      };
      // 根据100个切片创造100个请求（集合）
      let requestList = [];
      this.partList.forEach((item, index) => {
        // 每个函数都是发送一个切片的请求
        let fn = () => {
          let formData = new FormData();
          formData.append("file", item.chunk);
          formData.append("filehash", item.filename);
          this.Total += index;
          return FileUpload(formData, query);
        };

        requestList.push(fn);
      });
      // 传递切片：并行/串行(基于标志控制不发送)
      let i = 0; // 传了多少
      let complete = async () => {
        // 所有切片传完，合并切片
        let result = await MegerChunks(this.hash, this.fileName, query);
        if (result.data.code == 200) {
          this.Total = 0;
          this.all();
        } else {
          console.log(result)
          this.$message({
            message: result.data.message,
            type: "warning",
            center: true
          });
        }
      };

      // 开始上传
      let send = async () => {
        // 已经中断则不再上传
        if (this.abort) return;
        if (i >= requestList.length) {
          // 都传完了
          complete();
          return;
        }
        await requestList[i](); // 当前切片发送给服务器
        i++;
        send();
      };
      send();
    },

    // 删除
    fileDel(fileinfo) {
      let bucketname = fileinfo.bucket_name;
      let catalogue_name = fileinfo.catalogue_name;
      let object_name = fileinfo.file_name;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.loading = true;
          FileDel(bucketname, catalogue_name, object_name)
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: res.data.data,
                  center: true
                });
                this.all();
              } else {
                this.$message({
                  message: res.data.message,
                  type: "warning",
                  center: true
                });
                this.all();
              }
            })
            .catch(err => {
              this.$message.error(err);
              this.loading = false;
            });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除"
          // });
        });
    },
    /**加载所有文件 */
    all() {
      let bucket_name = this.$route.query.bucketname;
      // let bucketid = this.$route.query.bucketid;
      let catalogue_name = this.$route.query.rootdir;
      this.loading = true;
      ObjectAll(
        bucket_name,
        catalogue_name,
        this.paginationData.page,
        this.paginationData.limit
      )
        .then(res => {
          if (res.data.code == 200) {
            this.loading = false;
            this.fileInfos = res.data.data;
            this.paginationData.total = res.data.Count;
          } else {
            this.$message({
              message: res.data.message,
              type: "warning",
              center: true
            });
            this.loading = false;
          }
        })
        .catch(err => {
          this.$message.error(err);
          this.loading = false;
        });
    },

    /**文件搜索 */
    SearchFile() {
      let bucket_name = this.$route.query.bucketname;
      let object_name = this.searchFile;
      let catalogue_name = this.$route.query.rootdir;
      SearchFiles(
        object_name,
        catalogue_name,
        bucket_name,
        this.limit,
        this.page
      )
        .then(res => {
          if (res.data.code == 200) {
            this.fileInfos = res.data.data;
          } else {
            this.$message({
              message: res.data.message,
              type: "warning",
              center: true
            });
          }
        })
        .catch(err => {
          this.$message.error("请输入需要查询的文件名称");
          this.all();
        });
    },
    // 下载
    download(row) {
      DownloadFile(row.id, row.bucket_name, row.catalogue_name)
        .then(res => {
          if (res.status == 200) {
            let blob = new Blob([res.data], {
              type: res.data.type
            });

            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, row.file_name);
            } else {
              var link = document.createElement("a");
              link.href = window.URL.createObjectURL(blob);
              link.download = row.file_name;
              link.click();
              //释放内存
              window.URL.revokeObjectURL(link.href);
            }
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    // // 一页显示多少条数据
    // handleSizeChange(val) {
    //   this.page = val;
    //   this.all();
    // },

    // 下一页
    // nextChange() {
    //   this.limit += this.page;
    //   this.all();
    // },
    // // 上一页
    // prevChange(val) {
    //   if (val == 1) {
    //     this.limit = 1;
    //   } else {
    //     this.limit = this.page - 10;
    //   }
    //   this.all();
    // },
    // handleCurrentChange(val) {
    //   if (val == 1) {
    //     this.limit = 1;
    //   } else {
    //     this.limit = this.limit + 10;
    //   }
    //   this.all();
    // },
    // 分享
    share_create(row) {
      let query = {
        bucket_name: row.bucket_name,
        catalogue_name: row.catalogue_name,
        expiration: 3600,
        object_name: row.file_name
      };
      ShareFile(query)
        .then(res => {
          if (res.data.code == 200) {
            this.shareURL = res.data.data.share_url;
            this.Share_success_dialogVisible = true;
          } else {
            this.$message({
              message: res.data.message,
              type: "warning",
              center: true
            });
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    // 复制事件
    share_copy() {
      let _this = this;
      const clipboard = new Clipboard(".copy-link");
      clipboard.on("success", function(e) {
        _this.$message({
          message: "复制成功",
          type: "success",
          center: true
        });
        // 释放内存
        clipboard.off("error");
        clipboard.off("success");

        clipboard.destroy();
      });
      clipboard.on("error", function(e) {
        _this.$message({
          message: "复制失败",
          type: "warning",
          center: true
        });
        // 释放内存

        clipboard.off("error");
        clipboard.off("success");
        clipboard.destroy();
      });
    },
    /**
     * currentPage 改变时会触发事件
     * @param {Object} currentPage
     */
    handleCurrentChange(currentPage) {
      let bucket_name = this.$route.query.bucketname;
      // let bucketid = this.$route.query.bucketid;
      let catalogue_name = this.$route.query.rootdir;
      this.loading = true;
      ObjectAll(
        bucket_name,
        catalogue_name,
        currentPage,
        this.paginationData.limit
      )
        .then(res => {
          if (res.data.code == 200) {
            this.loading = false;
            this.fileInfos = res.data.data;
            this.paginationData.total = res.data.Count;
          } else {
            this.$message({
              message: res.data.message,
              type: "warning",
              center: true
            });
            this.loading = false;
          }
        })
        .catch(err => {
          this.$message.error(err);
          this.loading = false;
        });
    },
    /**
     * pageSize 改变时会触发事件
     * 下拉选择多少页
     * @param {Object} pageSize
     */
    handleSizeChange(pageSize) {
 

      let bucket_name = this.$route.query.bucketname;
      // let bucketid = this.$route.query.bucketid;
      let catalogue_name = this.$route.query.rootdir;
      this.loading = true;
      ObjectAll(
        bucket_name,
        catalogue_name,

        this.paginationData.page,
        pageSize
      )
        .then(res => {
          if (res.data.code == 200) {
            this.loading = false;
            this.fileInfos = res.data.data;
            this.paginationData.total = res.data.Count;
          } else {
            this.$message({
              message: res.data.message,
              type: "warning",
              center: true
            });
            this.loading = false;
          }
        })
        .catch(err => {
          this.$message.error(err);
          this.loading = false;
        });
    },
    /**上传照片 */
    uploadPhoto(e) {
      // 利用fileReader对象获取file
      var file = e.target.files[0];
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = e => {
        // 读取到的图片base64 数据编码 将此编码字符串传给后台即可
        var imgcode = e.target.result;
        this.form.photograph = imgcode;
      };
    }
  },

  mounted() {
    this.all();
    // 分享链接复制事件
  }
};
</script>

<style lang="less" scoped>
.breadcrumb {
  margin-bottom: 10px;
}
.menu {
  margin-top: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;

  > li > div {
    width: 140px;
    text-align: center;
    > span {
      font-size: 12px;
    }
  }
}

.func {
  display: flex;
}

.menu-have-img {
  // border: 1px solid #000;
  display: flex;
  z-index: 0;
  height: 0;
  margin-left: 15px;
  position: relative;
  .menu-have-img-more {
    z-index: 0;
    margin-left: auto;
    cursor: pointer;
    position: absolute;
    // right: 20px;
    right: 0;

    > ul {
      // display: none;
      color: #c2c2c2;
      font-size: 14px;
      > li {
        // padding: 0 5px;
        margin-bottom: 6px;
        // text-align: center;
      }
      > li:hover {
        color: #f40;
      }
    }
  }
}
.share_font {
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-block: 15px;
}
</style>